package com.example.main.login

import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.lib_base.mvvm.BaseViewActivity
import com.example.main.R
import com.example.main.databinding.ActivityLoginBinding
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.PopupMenu
import com.blankj.utilcode.util.SPUtils
import com.example.lib_base.http.Cont
import com.example.lib_base.mvvm.BaseActivity
import com.example.lib_base.mvvm.BaseViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlin.math.log
@AndroidEntryPoint
@Route(path = "/login/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    override fun initData() {
        vm.LoginSuccess.observe(this){
            Log.d( "initData: ",it.toString())
            SPUtils.getInstance().put("uid",it.id)
            SPUtils.getInstance().put(Cont.TOKEN,it.token)
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
            ARouter.getInstance().build("/main/MainActivity").navigation()
            finish()
        }


    }

    override fun initView() {
        // 指纹登录
        binding.llFingerprint.setOnClickListener {
            showBiometricPrompt()
        }
        binding.tvForgetPwd.setOnClickListener {
            showPopupMenu(it)
        }
        // 微信登录
        binding.llWechat.setOnClickListener { doWeChatLogin() }
        binding.llQq.setOnClickListener { doQQLogin() }
        binding.llAlipay.setOnClickListener { doAlipayLogin() }
        // 注册
        binding.tvRegister.setOnClickListener {
            ARouter.getInstance().build("/login/RegisterActivity").navigation()
        }
        binding.btnLogin.setOnClickListener {
            val phone = binding.etUsername.text.toString()
            val pwd = binding.etPassword.text.toString()

            if (phone.isEmpty() || pwd.isEmpty()) {
                showLoginErrorDialog()
            } else {
                vm.loginlist(phone, pwd)
            }


        }
    }

    // 判断用户是否合法（此处仅为示例，实际应替换为你的校验逻辑）
    private fun isUserValid(phone: String, pwd: String): Boolean {

        return false
    }

    // 显示温馨提示对话框
    private fun showLoginErrorDialog() {
        AlertDialog.Builder(this)
            .setTitle("温馨提示")
            .setMessage("手机号或密码错误，或未注册，请检查后重试")
            .setPositiveButton("知道了") { dialog, _ -> dialog.dismiss() }
            .setCancelable(false)
            .show()
    }

    private fun showBiometricPrompt() {
        val biometricManager = BiometricManager.from(this)
        if (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)
            == BiometricManager.BIOMETRIC_SUCCESS) {
            val promptInfo = BiometricPrompt.PromptInfo.Builder()
                .setTitle("指纹登录")
                .setSubtitle("请验证指纹以登录")
                .setNegativeButtonText("取消")
                .build()
            val biometricPrompt = BiometricPrompt(this, ContextCompat.getMainExecutor(this),
                object : BiometricPrompt.AuthenticationCallback() {
                    override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                        super.onAuthenticationSucceeded(result)
                        Toast.makeText(this@LoginActivity, "指纹验证成功，正在跳转...", Toast.LENGTH_SHORT).show()
                        ARouter.getInstance().build("/main/MainActivity").navigation()
                        finish()
                    }
                    override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                        super.onAuthenticationError(errorCode, errString)
                        Toast.makeText(this@LoginActivity, "指纹验证失败: $errString", Toast.LENGTH_SHORT).show()
                    }
                })
            biometricPrompt.authenticate(promptInfo)
        } else {
            Toast.makeText(this, "当前设备不支持指纹登录", Toast.LENGTH_SHORT).show()
        }
    }

    // 微信登录
    private fun doWeChatLogin() {
        // TODO: 调用微信SDK发起登录请求
        // 示例：
        // val req = SendAuth.Req()
        // req.scope = "snsapi_userinfo"
        // req.state = "wechat_sdk_demo"
        // wxApi.sendReq(req)
        // 登录成功回调中调用 onWeChatLoginSuccess()
        Toast.makeText(this, "微信登录功能待完善", Toast.LENGTH_SHORT).show()
    }

    // QQ登录
    private fun doQQLogin() {
        // TODO: 调用QQ SDK发起登录请求
        // 示例：
        // mTencent.login(this, "all", qqLoginListener)
        // 登录成功回调中调用 onQQLoginSuccess()
        Toast.makeText(this, "QQ登录功能待完善", Toast.LENGTH_SHORT).show()
    }

    // 支付宝登录
    private fun doAlipayLogin() {
        // TODO: 调用支付宝SDK发起登录请求
        // 示例：
        // AlipaySDK.login(this, alipayLoginCallback)
        // 登录成功回调中调用 onAlipayLoginSuccess()
        Toast.makeText(this, "支付宝登录功能待完善", Toast.LENGTH_SHORT).show()
    }

    // 微信登录成功回调
    private fun onWeChatLoginSuccess() {
        Toast.makeText(this, "微信登录成功", Toast.LENGTH_SHORT).show()
        ARouter.getInstance().build("/main/MainActivity").navigation()
        finish()
    }
    // QQ登录成功回调
    private fun onQQLoginSuccess() {
        Toast.makeText(this, "QQ登录成功", Toast.LENGTH_SHORT).show()
        ARouter.getInstance().build("/main/MainActivity").navigation()
        finish()
    }
    // 支付宝登录成功回调
    private fun onAlipayLoginSuccess() {
        Toast.makeText(this, "支付宝登录成功", Toast.LENGTH_SHORT).show()
        ARouter.getInstance().build("/main/MainActivity").navigation()
        finish()
    }
    private fun showPopupMenu(view: View) {
        // 创建 PopupMenu 对象
        val popupMenu = PopupMenu(this, view)

        // 填充菜单项
        popupMenu.menuInflater.inflate(R.menu.popup_menu, popupMenu.menu)

        // 设置菜单项点击事件
        popupMenu.setOnMenuItemClickListener { item: MenuItem ->
            when (item.itemId) {
                R.id.menu_yes -> {
                    Toast.makeText(this, "找回密码", Toast.LENGTH_SHORT).show()
                    true
                }
                R.id.menu_no -> {
                     ARouter.getInstance().build("/login/ForgetPWActivity").navigation()
                    true
                }
                else -> false
            }
        }

        // 显示弹出菜单
        popupMenu.show()
    }
}